<?php

class sinaModel
{

    /**
     * 基类
     * @var object
     */
    private $base;

    /**
     * Mysql 连接
     * @var resources
     */
    private $db;

    /**
     * Redis 连接
     * @var resources
     */
    private $redis;

    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
    }

    static $sina_url = array(
        'userinfo' => 'https://api.weibo.com/2/users/show.json',
        'friends' => 'https://api.weibo.com/2/friendships/friends/ids.json'
    );

    /**
     * 绑定新浪用户
     * @param type $sinaData
     * @param type $uid
     */
    public function saveUser($sina_id, $token)
    {
        $url = self::$sina_url['userinfo'];
        $query['uid'] = $sina_id;
        $query['access_token'] = $token;

        $info = common::getContents($url, $query);
        $sinaUserinfo = json_decode($info, true);
        $genderMap = array('m' => 1, 'f' => 2, 'n' => 0);

        $uid = $this->base->uid;

        $time = time();

        if(isset($sinaUserinfo['error'])){
            $this->base->result['error'] = array(
                'id' => $sinaUserinfo['error_code'],
                'text' => '接口错误：'.$sinaUserinfo['error'],
            );
            exit();
        }
        //插入新用户
        $social_data = array(
            'channel' => 3,
            'openid' => $sinaUserinfo['id'],
            'access_token' => $token,
            'nickname' => $sinaUserinfo['name'],
            'header' => $sinaUserinfo['avatar_large'],
            'expires' => '',
            'create_time' => $time,
            'last_time' => $time,
            'is_bind' => 1
        );

        //插入绑定数据
        $sid = $this->base->db->insertRowTable('r_social_user', $social_data);
        $uid = $this->base->db->getone("select uid from r_user where sina = '{$sid}'");
        if($uid)
        {
            if(!empty($this->base->uid))
            {
                if($uid == $this->base->uid)
                {
                    $data = $_ENV['client']->getUserInfo($uid);
                }
                else
                {
                    $_ENV['error']->getErrors(202);
                    exit;
                }
            }
            else
            {
                $this->base->uid = $uid;
                $data = $_ENV['client']->getUserInfo($uid);
            }
        }
        else
        {
            unset($uid);
            $vid = $this->base->vid;
            //获取之前的游客数据
            $data = $this->db->getRowTable('r_visitor', array(), "vid={$vid}");
            if(!empty($data))
            {
                unset($data['vid'],$data['old_uid']);
            }
        }
        if(empty($data))
        {
            $data = array(
                'height' => 170,
                'weight' => 60,
                'age' => 18,
                'gender' => 1,
                'total_mileage' => 0,
                'total_elapsedtime' => 0,
                "total_calorie" => 0,
                'total_rate' => 0,
                'max_mileage' => 0,
                'max_elapsedtime' => 0,
                'max_speed' => 0,
                'addtime' => time(),
                'cid' => $this->base->cid,
                'lastcid' => $this->base->cid,
                'qq' => 0,
                'sina' => 0,
                'weixin' => 0,
                'renren' => 0
            );
        }
        $data['sina'] = $sid;
        $data['nickname'] = $sinaUserinfo['name'];
        $data['header'] = $sinaUserinfo['avatar_large'];
        $data['addtime'] = time();

        $checkNickname = $this->base->checkNickname($data['nickname']);

        if($checkNickname == -3)//昵称重复
        {
            $data['nickname'] .= 'S'.str_pad(rand(0, 9999), 4, '0',STR_PAD_LEFT);
        }
        elseif($checkNickname < 0)
        {
            $errorId = 500 - $checkNickname;
            $_ENV['error']->getErrors($errorId);
            exit;
        }
        //$newuid = $this->base->db->insertRowTable('r_user', $data);
        $newuid = $this->base->load('user')->insert($data);

        if ($newuid)
        {
            $this->base->uid = $newuid;
            $_ENV['client']->setUserInfo($newuid, $data);
            //转移数据
            isset($vid) && $this->base->turnRunData($newuid, $vid);
            //更新排行
            $this->base->load("run")->setClientMileageStandingsRank($newuid, $data['total_mileage']);
        }

        $tokenStr = md5($newuid . $time . $sina_id . md5(time() . $sina_id));
        $tokenArr = array($newuid, $time, $tokenStr);
        $token = implode('-', $tokenArr);

        $return_data = array();
        $return_data['token'] = $token;
        $return_data['sid'] = $sina_id;
        $return_data['key'] = md5(time() . $sina_id);
        return $return_data;
    }

    /**
     * 保存新浪用户名
     * @param type $nickName
     */
    private function saveNickname($nickName)
    {
        $checkNickname = $this->base->checkNickname($nickName);


        if ($checkNickname != 1)
        {
            $errorId = 100;

            switch ($checkNickname) {
                case -1:
                    $errorId = 501;
                    break;

                case -2:
                    $errorId = 502;
                    break;

                case -3:
                    $errorId = 503;
                    break;
            }

            $_ENV['error']->getErrors($errorId);
            exit;
        }

        return $nickName;
    }

    /**
     * 保存球员对象
     * @param type $url
     */
    private function saveProfile($url)
    {
        $result = FALSE;

        $day = date('Ymd');
        $fix = 'jpg';
        $upPath = FILE . '../web/static/u/' . $day . '/';

        if (!is_dir($upPath))
        {
            mkdir($upPath);
        }
        $fileName = md5($url . microtime(TRUE)) . '.' . $fix;
        $upFileName = $upPath . $fileName;

        if (file_put_contents($upFileName, $url))
        {
            $result = 'http://' . $this->base->config['host'] . '/static/u/' . $day . '/' . $fileName;
        }

        return $result;
    }

    /**
     * 保存新浪好友
     */
    public function saveFriends($sina_id, $token, $uid)
    {
        $url = self::$sina_url['friends'];
        $query['uid'] = $sina_id;
        $query['access_token'] = $token;

        $info = common::getContents($url, $query);

        $sinaUserinfo = json_decode($info, true);
        
        $sqlStr = '';
        foreach ($sinaUserinfo['ids'] as $id){
            $sqlStr .= "({$uid}, {$sina_id}, '', {$id}, 0),";
        }
        
        $sql = "replace into r_sina_user values ". $sqlStr . "($uid, $sina_id, '', $sina_id, 0)";
        $this->db->update($sql);
        //更新好友uid
        $sql = "update r_user u,r_sina_user su set su.f_uid = u.uid,su.mileage = u.total_mileage where su.sid_friend = u.sid";
        $this->db->update($sql);
        return ;
    }
    
    

}